<template>
  <div class="search-input">
    <Input
      v-model="value"
      :maxlength="maxLength"
      :placeholder="placeholder"
      :readonly="readonly"
      search
      :enter-button="button"
      @on-change="changeValue(value)"
      @on-search="search"
      @keydown.native.enter.prevent="onKeyDown"
    >
    </Input>
  </div>
</template>

<script>
export default {
  props: {
    placeholder: {
      type: String,
      default: '请输入关键字'
    },
    readonly: {
      type: Boolean,
      default: false
    },
    button: {
      type: String,
      default: '查询'
    },
    maxLength: {
      type: Number,
      default: 100
    },
    content: {
      type: String,
      default: ''
    }
  },
  watch: {
    content (value) {
      this.value = value
    }
  },
  data () {
    return {
      value: this.content,
      // 是否是回车触发
      isEnterDown: false
    }
  },
  methods: {
    changeValue (value) {
      this.$emit('update:content', value)
    },
    onKeyDown (e) {
      this.isEnterDown = true

      // 如果绑定了回车时间，单独执行
      let enterDownEvent = this.$listeners.enterDown
      if (enterDownEvent) {
        enterDownEvent()
      } else {
        this.dealEvent()
      }
    },
    search () {
      if (this.isEnterDown) {
        this.isEnterDown = false
        return
      }

      this.dealEvent()
    },
    clear () {
      this.value = ''
      this.changeValue('')
    },
    dealEvent () {
      this.$emit('click-btn')
    }
  }
}
</script>

<style lang="less" scoped>
.search-input {
  position: relative;
  padding: 0;
  .search-btn {
    height: 32px;
    width: 50px;
    line-height: 32px;
    position: absolute;
    top: 0;
    right: 0;
    color: #fff;
    text-align: center;
    cursor: pointer;
  }
}
</style>
